# Definition for singly-linked list.
class ListNode:
  def __init__(self, x):
    self.val = x
    self.next = None


class Solution:
  def deleteNode(self, head: ListNode, val: int) -> ListNode:
    node_head = head
    node_prev, node_cur, node_next = head, head.next, head.next.next
    # 删除头节点的情况
    if node_head.val == val:
      node_head = node_head.next
    while node_next is not None:
      if node_cur.val == val:
        node_prev.next = node_next
      node_prev = node_prev.next
      node_cur = node_cur.next 
      node_next = node_next.next 
    # 遍历一遍后，检查是否需要删除尾节点
    if node_cur.val == val:
      node_prev.next = None
    return node_head


def print_nodes(head: ListNode):
  while head is not None:
    print(head.val, end=' ')
    head = head.next
  print('')


'''
STATUS: SOLVED
TRIES:  1
TIME:   44 MS
MEMORY: 14 MB
'''
if __name__ == "__main__":
  list_node = ListNode(6)
  list_node_head = list_node
  for i in [5, 4, 3, 2, 1]:
    list_node.next = ListNode(i)
    list_node = list_node.next
  solution = Solution()
  res = solution.deleteNode(head=list_node_head, val=4)
  print_nodes(res)
